package com.system.es;

import com.system.util.ReflectUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author X.I.O
 * @title: MapUtils
 * @projectName springboot
 * @description: TODO
 * @date 2022/1/25 14:32
 */
public class MapUtils {

    public  static <T> Map<String, Object> getMap(T t){
        Field[] fields= t.getClass().getDeclaredFields();
        Map<String, Object> map=new HashMap<>();
        try {
            for (int i = 0; i < fields.length; i++) {
                Field field=fields[i];
                field.setAccessible(true);
                String fieldName = field.getName();
                Object value=field.get(t);
                map.put(fieldName,value);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    /**
     *
     * @param map
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T getObject(Map<String, Object> map,Class<T> tClass){
        if(map==null || map.isEmpty()){
            return null;
        }
        Field[] fields=tClass.getDeclaredFields();
        T t=null;
        try {
            t=tClass.newInstance();
            for(Map.Entry<String, Object> objMap: map.entrySet()){
                String key=objMap.getKey();
                Object value=objMap.getValue();
                ReflectUtils.setObjectData(t,fields,key,value);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return t;
    }
}
